<?php
    header('content-type:text/html;charset-utf-8');

    $host = 'localhost:3306' ;
    $name = $pwd = 'root' ;
    $dbname = 'day24' ;
    $conn = mysqli_connect($host , $name , $pwd , $dbname) ;

    if(!$conn) {
        die('数据库连接失败');
    }

    $uname = $_POST['username'];
    $id = $_POST['goods_id'];
    $num = $_POST['num'];
    $color = $_POST['color'];
    $size = $_POST['size'];

    $obj = [];


    if($uname && $id && $num && $color && $size){

        $sql = "select * from cart where goods_id = $id and username = '$uname' and color = '$color' and size = '$size'";
        $res = mysqli_query($conn,$sql);
        $arr = mysqli_fetch_array($res);

        if($arr){
            $sql = "UPDATE cart set cart_num = cart_num + $num where username = '$uname' and goods_id = $id  and color = '$color' and size = '$size'";
            mysqli_query($conn ,$sql);
            $rows = mysqli_affected_rows($conn);

            if($rows>0){
                $obj['status'] = true ;
                $obj['msg'] = '成功加入购物车';

            }else{
                $obj['status'] = false ;
                $obj['msg'] = '加入购物车失败';
            }
        }else{
            $sql = "insert into cart (username , goods_id , cart_num ,color , size) values ('$uname' , $id , $num , '$color' , '$size')" ;
            mysqli_query($conn , $sql) ;
            // 受影响的行数
            $rows = mysqli_affected_rows($conn) ;
            if($rows > 0) {
                $obj['status'] = true ;
                $obj['msg'] = '成功加入购物车';
            } else {
                $obj['status'] = false ;
                $obj['msg'] = '服务器错误';
            }
        }

    }else{
        $obj['status'] = false ;
        $obj['msg'] = '前端数据有误';
    }


    echo(json_encode($obj,JSON_UNESCAPED_UNICODE));
?>